// Copyright (c) 2023 Presto Labs Pte. Ltd.
// Author: tianqiang

#include "coin2/exchange/maicoin/api_order/native_rest_async_asio_subscriber.h"

namespace coin2::exchange::maicoin::api_order {

void MaicoinRestAsyncAsioSubscriber::QueryAccountBalance() {
  auto http_context = rest_client()->QueryAccountBalance();
  if (!http_context) {
    return;
  }
  http_context->handler =
      std::bind(&MaicoinRestAsyncAsioSubscriber::HandleQuery, this, std::placeholders::_1);
  http_driver_->PostAsyncContext(http_context);
}

void MaicoinRestAsyncAsioSubscriber::QueryOpenOrders() {
  auto http_context = rest_client()->QueryOpenOrders();
  if (!http_context) {
    return;
  }
  http_context->handler =
      std::bind(&MaicoinRestAsyncAsioSubscriber::HandleQuery, this, std::placeholders::_1);
  http_driver_->PostAsyncContext(http_context);
}

void MaicoinRestAsyncAsioSubscriber::QueryHistoryOrders(const std::string& native_symbol) {
  RestParams params;
  params.set_market(native_symbol);

  auto http_context = rest_client()->QueryHistoryOrders(params);
  if (!http_context) {
    return;
  }
  http_context->handler =
      std::bind(&MaicoinRestAsyncAsioSubscriber::HandleQuery, this, std::placeholders::_1);
  http_driver_->PostAsyncContext(http_context);
}

void MaicoinRestAsyncAsioSubscriber::QueryFills() {
  auto http_context = rest_client()->QueryFills();
  if (!http_context) {
    return;
  }
  http_context->handler =
      std::bind(&MaicoinRestAsyncAsioSubscriber::HandleQuery, this, std::placeholders::_1);
  http_driver_->PostAsyncContext(http_context);
}

void MaicoinRestAsyncAsioSubscriber::SubscribeAsync() {
  const auto symbols = native_symbols();

  AddPeriodicTask(
      std::bind(&MaicoinRestAsyncAsioSubscriber::QueryAccountBalance, this),
      config_.query_account_balance_period_sec(),
      "query_balance");

  AddPeriodicTask(
      std::bind(&MaicoinRestAsyncAsioSubscriber::QueryOpenOrders, this),
      config_.query_open_orders_period_sec(),
      "query_open_orders");

  AddPeriodicTask(
      std::bind(&MaicoinRestAsyncAsioSubscriber::QueryHistoryOrders, this, std::placeholders::_1),
      config_.query_cancel_orders_period_sec(),
      "query_history_orders",
      symbols);

  AddPeriodicTask(
      std::bind(&MaicoinRestAsyncAsioSubscriber::QueryFills, this),
      config_.query_fill_period_sec(),
      "query_fills");
}

}  // namespace coin2::exchange::maicoin::api_order
